package com.camel.gateway.config;

import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @author camel
 */
@Configuration
public class SaTokenConfigure {

    @Autowired
    private AuthIgnore authIgnore;

    protected static Logger logger = LoggerFactory.getLogger(SaTokenConfigure.class);

    /**
     * 注册 Sa-Token全局过滤器
     **/
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                // 拦截地址
                // 拦截全部path
                .addInclude("/**")
                // 开放地址
                .addExclude("/favicon.ico", "/WMCenter/**", "/api/base/**")

                // 鉴权方法：每次访问进入
                .setAuth(obj -> {


                    logger.info("收到请求并携带TOKEN: {}" , StpUtil.getTokenValue());

                    try {
                        SaRouter.match("/**").notMatch(authIgnore.getUrls()).check(r -> {
                            if(StringUtils.isEmpty(StpUtil.getTokenValue())) {
                                throw new RuntimeException("未登录");
                            }
                            StpUtil.checkLogin();
                        });
                    } catch (Exception e) {
                        throw e;
                    }
                    // 权限认证 -- 不同模块, 校验不同权限
                    SaRouter.match("/api/system/sysParam/**", r -> StpUtil.checkPermission("system/Variable"));
                    SaRouter.match("/api/system/sysUser/**", r -> StpUtil.checkPermission("system/user"));
                    SaRouter.match("/api/system/sysRole/**", r -> StpUtil.checkPermission("system/Role"));
                    SaRouter.match("/api/system/sysCompany/**", r -> StpUtil.checkPermission("system/Dept"));

                    // 更多匹配 ...  */
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e -> {
                    SaResult error = SaResult.error(e.getMessage());
                    error.setCode(401);
                    return error;
                });
    }
}
